package com.emm.yixun.customer.service.impl.app.manage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.mapper.BaseCodeValueMapper;
import com.emm.yixun.basic.mapper.CustomerMapper;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.RoleService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.GetSearchListReqDto;
import com.emm.yixun.common.app.GetSearchListResDto;
import com.emm.yixun.common.app.servletentity.CustomerListRes;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.appDto.CustomerCountDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.CustomerStarEnum;
import com.emm.yixun.common.model.enums.CustomerStatusEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IntentionLevelEnum;

@Service("getSearchListManage")
public class GetSearchListManage {

	@Autowired
	private CustomerService customerService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private CustomerMapper customerMapper;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private BaseCodeValueMapper baseCodeValueMapper;
	
	/**
	 * 查询客户列表
	 * 以客户姓名或客户电话进行模糊匹配
	 * @param reqDto
	 * @return
	 */
	public GetSearchListResDto getSearchList(GetSearchListReqDto reqDto) {
		GetSearchListResDto resDto = new GetSearchListResDto();
		try{
			CustomerDto customerDto = new CustomerDto();
			customerDto.setMerchantId(reqDto.getMerchantId());
			customerDto.setProjectCode(reqDto.getProjectCode());
			customerDto.setSearchContent(reqDto.getSearchContent());
			customerDto.setUserId(Long.valueOf(reqDto.getUserId()));

			List<Customer> getList = null;
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			cusCountDto.setUserId(reqDto.getUserId());
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			if(user != null){
				cusCountDto.setUserCode(user.getUserCode());
			}
			cusCountDto.setSearchContent(reqDto.getSearchContent());
			/**
			 * 客户搜索添加数据权限
			 * JHSong_2016-10-21_操作: 添加代码块
			 * jzliu_2018-10-21_操作：修改原权限为：查询所属项目下所有数据，并判断是否有权限进行操作
			 */
			String dataPermission = null;
			if("2".equals(reqDto.getCusType())){//逾期未签约
				dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), "menu_0100_0001", "t", null);
			}else if("3".equals(reqDto.getCusType())){//逾期未付款
				dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), "menu_0100_0002", "t", null);
			}else{
				dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), "menu_0006_0001", "t", null);
			}
			String [] str_permission = dataPermission.split(":");
			if("00".equals(str_permission[0])
					|| str_permission[1].indexOf("1=2") >= 0){
				resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERNOEXIST.getCode());
				resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERNOEXIST.getDesin());
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			if(!"1".equals(reqDto.getCusType())){
				//cusCountDto.setDataPermission(str_permission[1]);
			}

			if(reqDto.getCusType() != null && "1".equals(reqDto.getCusType())){//待处理客户
				getList = customerMapper.selectSearchCustomerByList(cusCountDto);
			}else if(reqDto.getCusType() != null && "2".equals(reqDto.getCusType())){//逾期未签约
				getList = customerMapper.selectSearchSubscribeCustomerByList(cusCountDto);
			}else if(reqDto.getCusType() != null && "3".equals(reqDto.getCusType())){//逾期未付款
				getList = customerMapper.selectSearchPaymentCustomerByList(cusCountDto);
			}else{
				//customerDto.setDataPermission(str_permission[1]);
				getList = customerService.getCustomerByFuzzyQuery(customerDto);
			}

			List<CustomerListRes> customerList = new ArrayList<CustomerListRes>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for(Customer customer: getList){
				CustomerListRes clRes = new CustomerListRes();
				clRes.setCustomerId(String.valueOf(customer.getId()));
				clRes.setCustomerName(customer.getCustomerName());
				if(StringUtils.isNotEmpty(customer.getCustomerStar())){
					clRes.setStar(CustomerStarEnum.getByNo(customer.getCustomerStar()).getDes());
				}
				if(StringUtils.isNotEmpty(customer.getIntentionLevel())){
					clRes.setIntentionLevel(IntentionLevelEnum.getByNo(customer.getIntentionLevel()).getDes());
				}
				if(StringUtils.isNotEmpty(customer.getCustomerOrigin())){
					BaseCodeValue baseCodeValue = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCustomerOrigin()));
					if(baseCodeValue != null){
						clRes.setCustomerOrigin(baseCodeValue.getCodeName());
					}
				}
				if(StringUtils.isNotEmpty(customer.getCustomerStatus())){
					clRes.setCustomerStatus(CustomerStatusEnum.getByNo(customer.getCustomerStatus()).getDes());
				}
				if(customer.getCreateTime() != null){
					clRes.setCreateTime(sdf.format(customer.getCreateTime()));
				}
				clRes.setMobile(customer.getCustomerPhone());
				//归属人姓名
				UserDto userDto = new UserDto();
				userDto.setUserCode(customer.getUserCode());
				userDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				User userEntity = userService.selectByDto(userDto);
				if(userEntity != null){
					clRes.setAttributionName(userEntity.getUserName());
				}else{
					clRes.setAttributionName(null);
				}
				//判断是否拥有查看权限
				GetCustomerListManage getCustomerListManage = new GetCustomerListManage();
				clRes.setDataAuthority(
						getCustomerListManage.dataAuthority(
								customer.getAccessCode(),
								customer.getUserCode(),
								customer.getSalesGroupId() == null ?null:customer.getSalesGroupId().toString(),
								str_permission[1])
				);
				customerList.add(clRes);
			}
			resDto.setCustomerList(customerList);
			resDto.setResult("1");
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("查询客户失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
}
